package org.infosec.lc.exercises.castor.dome;

import java.io.IOException;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.infosec.lc.exercises.castor.modle.Person;

/**
	文件名：CastorUDPSend.java
	作  者：林超
	时  间：2011-7-19下午03:47:02

	功能描述：模拟UDP服务端发出，通过Castor-Marshaller将Person转换为XML数据流
	
	pom.xml	:
			
 */
public class CastorUDPSend {

	private Person person;
	private DatagramSocket socket;
	private DatagramPacket packet;
	
	{
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public CastorUDPSend(Person person) {
		this.person = person;
	}
	
	public CastorUDPSend() {
		super();
	}
	
	public void send(){
		try {
			check();
			
			StringWriter string = new StringWriter();
			Marshaller.marshal(person,string);
			
			System.out.println(string.toString());
			
			sendUDP(string.toString().getBytes());
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		}
	}
	
	private void check(){
		if(person == null){
			throw new NullPointerException("person is null");
		}
		if(socket == null){
			throw new NullPointerException("socket is null");
		}
	}
	
	private void sendUDP(byte[] date){
		try {
			
			packet = new DatagramPacket(date,0,date.length);
			packet.setAddress(InetAddress.getLocalHost());
			packet.setPort(5000);
			
			socket.send(packet);
			socket.close();
			
			System.out.println("已发送完成！");
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Person p = new Person();
		p.setName("a");
		
		CastorUDPSend castor = new CastorUDPSend(p);
		castor.send();

	}
}

